1342E - Placing Rooks - CodeForces Solution


combinatorics fft math *2300

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using ll=long long;
const ll mod=998244353;
ll mod_pow(ll a,ll n,ll mod)
{
	ll ans=1;
	a%=mod;
	while(n)
	{
		if(n&1)ans=(ans*a)%mod;
		a=(a*a)%mod;
		n>>=1;
	}
	return ans%mod;
}
ll mod_mul(ll a,ll b,ll mod)
{
	a%=mod;
	b%=mod;
	ll ans=0;
	while(b)
	{
		if(b&1)ans=(ans+a)%mod;
		a=(a+a)%mod;
		b>>=1;
	}
	return ans%mod;
}
ll gcd(ll a,ll b)
{
	if(!b)return a;
	else return gcd(b,a%b);
}
ll exgcd(ll a,ll b,ll&x,ll&y)
{
	if(!b){x=1;y=0;return a;}
	else
	{
		ll d=exgcd(b,a%b,y,x);
		y-=(a/b)*x;
		return d;
	}
}
ll mod_inv(ll a,ll mod)
{
	ll x,y;
	exgcd(a,mod,x,y);
	return (x%mod+mod)%mod;
}
const int maxn=1e6+1e1;
ll f[maxn]{},inv_f[maxn]{};
void fact_init(int n,ll mod)
{
	f[0]=1;
	for(int i=1;i<=n;i++)
	{
		f[i]=f[i-1]*i%mod;
	}
	inv_f[n]=mod_inv(f[n],mod);
	for(int i=n-1;i>=0;i--)
	{
		inv_f[i]=inv_f[i+1]*(i+1)%mod;
	}
}
ll C(ll n,ll m)
{
	if(n<m)return 0;
	else 
	{
		ll ans=f[n];
		ans=mod_mul(ans,inv_f[m],mod);
		ans=mod_mul(ans,inv_f[n-m],mod);
		return ans;
	}
}
ll add(ll x,ll y)
{
	return (x+y)%mod;
}
ll sub(ll x,ll y)
{
	return add(x,mod-y);
}
void solve()
{
	ll n,k;std::cin>>n>>k;
	if(k>n-1)
	{
		std::cout<<0<<"\n";
		return;
	}
	fact_init(n,mod);
//	for(int i=1;i<=n;i++){std::cout<<f[i]<<" ";}std::cout<<"\n";
//	for(int i=1;i<=n;i++){std::cout<<inv_f[i]<<" ";}std::cout<<"\n";
	ll ans=0;
	ll c=n-k;
	for(ll i=c;i>=0;i--)
	{
		if(i%2==c%2)
		{
			ans=add(ans,mod_mul(mod_pow(i,n,mod),C(c,i),mod));
//			std::cout<<ans<<"\n";
		}
		else
		{
			ans=sub(ans,mod_mul(mod_pow(i,n,mod),C(c,i),mod));
//			std::cout<<ans<<"\n";
		}
	}
	ans=mod_mul(ans,C(n,c),mod);
//	std::cout<<ans<<"\n";
	if(k>0)ans=mod_mul(ans,2,mod);
	std::cout<<ans<<"\n";
}
int main()
{
	std::cin.tie(nullptr)->sync_with_stdio(false);
	solve();
	return 0;
}


Comments

Submit
0 Comments
More Questions

963A - Alternating Sum
1191B - Tokitsukaze and Mahjong
1612G - Max Sum Array
1459B - Move and Turn
1006F - Xor-Paths
706C - Hard problem
304C - Lucky Permutation Triple
1301C - Ayoub's function
38E - Let's Go Rolling
171G - Mysterious numbers - 2
1183C - Computer Game
400C - Inna and Huge Candy Matrix
417A - Elimination
222A - Shooshuns and Sequence
1736A - Make A Equal to B
1736B - Playing with GCD
887C - Solution for Cube
1737C - Ela and Crickets
1741C - Minimize the Thickness
1741A - Compare T-Shirt Sizes
1741D - Masha and a Beautiful Tree
109B - Lucky Probability
1741B - Funny Permutation
1741E - Sending a Sequence Over the Network
344B - Simple Molecules
370A - Rook Bishop and King
546E - Soldier and Traveling
1741G - Kirill and Company
1200B - Block Adventure
1088B - Ehab and subtraction